package com.tsl.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.databind.util.BeanUtil;
import com.tsl.reggie.anno.DeleteDishRedis;
import com.tsl.reggie.common.R;
import com.tsl.reggie.domain.dto.DishDto;
import com.tsl.reggie.domain.po.Category;
import com.tsl.reggie.domain.po.Dish;
import com.tsl.reggie.domain.po.DishFlavor;
import com.tsl.reggie.service.ICategoryService;
import com.tsl.reggie.service.IDishFlavorService;
import com.tsl.reggie.service.IDishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * <p>
 * 菜品管理 前端控制器
 * </p>
 *
 * @author 唐书亮
 * @since 2024-01-20
 */
@RestController
@RequestMapping("/dish")
public class DishController {
    @Autowired
    private IDishService dishService;
    @Autowired
    private IDishFlavorService dishFlavorService;
    @Autowired
    private ICategoryService categoryService;
    @Autowired
    private RedisTemplate redisTemplate;
    @PostMapping
    @DeleteDishRedis
    public R<String> saveDishFlavor(@RequestBody DishDto dishDto) {
        if (ObjectUtils.isEmpty(dishDto)) {
            return R.error("数据为空,无法保存");
        }
        R<String> R = dishService.saveDishFlavor(dishDto);
        return R;
    }

    @GetMapping("page")
    public R<Page<DishDto>> dishPage(Integer page, Integer pageSize, String name) {
        //构造分页查询条件
        Page<DishDto> dishDtoPage = new Page<>();
        Page<Dish> dishPage = new Page<>(page, pageSize);
        //构造条件构造器
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.like(name != null, Dish::getName, name);
        //调用service进行分页查询
        dishPage = dishService.page(dishPage, queryWrapper);
        //将Dish的分页查询赋值给DishDto
        BeanUtils.copyProperties(dishPage, dishDtoPage, "records");
        //处理dto里categoryName
        List<Dish> records = dishPage.getRecords();
        List<DishDto> dishDtoList = records.stream().map((item) -> {
            //获取Dish里的菜品id,然后根据id查询菜品分类
            Long categoryId = item.getCategoryId();
            Category category = categoryService.getById(categoryId);
            //将菜品分类封装到DishDto的categoryName里
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item, dishDto);
            dishDto.setCategoryName(category.getName());

            return dishDto;
        }).collect(Collectors.toList());
        dishDtoPage.setRecords(dishDtoList);
        //返回结果

        return R.success(dishDtoPage);
    }

    @GetMapping("/{id}")
    public R<DishDto> selectBack(@PathVariable Long id) {
        //调用service里的方法进行查询
        R<DishDto> dishDtoResult = dishService.selectBack(id);

        return dishDtoResult;
    }
    @DeleteDishRedis
    @PutMapping
    public R<String> updateDishWithFlavor(@RequestBody DishDto dishDto) {

        R<String> r = dishService.updateDishWithFlavor(dishDto);
        return r;
    }

    @GetMapping("list")
    public R<List<DishDto>> listDIsh(Dish dish) {
        List <DishDto> dishDtoList = null;
        //通过dishId和status构造key
        String key = "dishId_"+dish.getCategoryId()+"_"+dish.getStatus();
        //从redis里查询数据
        dishDtoList = (List<DishDto>) redisTemplate.opsForValue().get(key);
        //存在直接返回数据,不走数据库
        if (dishDtoList !=  null){
            return R.success(dishDtoList);
        }
        //不存在就从数据库里搜索
        //构造查询语句
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());
        queryWrapper.eq( Dish::getStatus, 1);
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        //查询结果
        List<Dish> list = dishService.list(queryWrapper);
        dishDtoList = list.stream().map((item) ->{
            //获取Dish里的菜品id,然后根据id查询菜品分类
            Long categoryId = item.getCategoryId();
            Category category = categoryService.getById(categoryId);
            //将菜品分类封装到DishDto的categoryName里
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item, dishDto);
            dishDto.setCategoryName(category.getName());

            Long id = item.getId();
            LambdaQueryWrapper<DishFlavor> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(DishFlavor::getDishId,id);
            List<DishFlavor> dishFlavors = dishFlavorService.list(queryWrapper1);
            dishDto.setFlavors(dishFlavors);
            return dishDto;

        }).collect(Collectors.toList());
        //返回查询结果
        redisTemplate.opsForValue().set(key,dishDtoList,60l, TimeUnit.MINUTES);
        return R.success(dishDtoList);
    }
}
